package com.lap.auth.configure;

import com.lap.auth.application.authentication.AuthQueryService;
import com.lap.auth.application.authorization.AuthorQueryService;
import com.lap.auth.filter.AuthenticationFilter;
import com.lap.auth.filter.AuthorizationFilter;
import com.lap.context.starter.core.helper.MessageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Configuration
public class AuthConfiguration {

  // 加密
  @Bean
  PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

  // ip restTemplate
  @Bean("ipHttpClientFactory")
  ClientHttpRequestFactory ipHttpClientFactory() {
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setConnectTimeout(3000);
    factory.setReadTimeout(3000);

    log.info("Initializer ip clientHttpRequest factory::{}", factory);
    return factory;
  }

  @Bean("ipRestTemplate")
  RestTemplate ipRestTemplate(@Qualifier("ipHttpClientFactory") ClientHttpRequestFactory factory) {
    log.info("Initializer ip restTemplate::{}", factory);
    return new RestTemplate(factory);
  }

  // TODO 单体
  @Bean
  AuthorizationFilter authorizationInterceptor(
      AuthorQueryService authorQueryService, MessageHelper messageHelder) {
    log.info("AuthorizationInterceptor enabled");
    return new AuthorizationFilter(authorQueryService, messageHelder);
  }

  @Bean
  AuthenticationFilter authenticationInterceptor(
      AuthQueryService authQueryService, MessageHelper messageHelder) {
    log.info("AuthenticationInterceptor enabled");
    return new AuthenticationFilter(authQueryService, messageHelder);
  }
}
